package com.edu.zql;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by User on 2017/10/13.
 */
public class TestVolatile  extends Thread{

    static int i = 0;

    private static boolean stopRequested;


    @Override
    public void run() {
        for (int j = 0; j < 100000; j++) {
            i++;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        dsa();
    }

    private static void aaa() throws InterruptedException {
        Thread backgroundThread = new Thread(new Runnable()
        {
            public void run()
            {
                int i = 0;
                while (!stopRequested) {
                    i++;
                }
            }
        });

        backgroundThread.start();

        TimeUnit.SECONDS.sleep(1);
        stopRequested = true;
    }

    /**
     * 使用volatile修饰i  输出2809657
     * 使用static修饰i或者不修饰i 输出4701547
     *
     */
    private static void dsa() {
        TestVolatile testVolatile = new TestVolatile();

        List<Thread> list = new ArrayList<Thread>();
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(testVolatile);
            list.add(thread);
        }
        for (Thread thread : list) thread.start();

        f:for (;;) {
            for (Thread thread : list )
                if (thread.isAlive()) continue f;
            break;
        }

        System.out.println(TestVolatile.i);
    }


}
